//
//  PersonalHomePageTableViewController.m
//  NewChat
//
//  Created by lanou3g on 16/3/1.
//  Copyright © 2016年 蓝鸥. All rights reserved.
//

#import "PersonalHomePageTableViewController.h"
#import "CommunityTableViewCell.h"
#import "HeadView.h"
#import "TopicTableViewCell.h"
#import "LReplyTableViewCell.h"
#import "CustomTwoBtnvView.h"
#import "ReplyViewController.h"
#import "MHDataHelper.h"
#import "SKXRongCloudManager.h"
#import "SKXChatViewController.h"
#import "SKXFriendManager.h"
#import "TopicTableViewController.h"
#import "PlayerManager.h"

@interface PersonalHomePageTableViewController ()

@property(nonatomic,strong)HeadView*headV;

@property(nonatomic,strong)CustomTwoBtnvView*bottomButton;


@property (nonatomic,strong)NSMutableArray *allHerTopics;
@property (nonatomic,strong)NSMutableArray *allHerReplys;
@property (nonatomic,strong)NSMutableArray *networkArray;//存放当前用户 关注的好友信息
@property (nonatomic,strong)AVUser *userModel;//存放当前页面用户信息
@property (nonatomic,strong)NSMutableArray *myFriendArray;//存放当前用户的 好友

@end

@implementation PersonalHomePageTableViewController

static BOOL flag = YES;

//懒加载
-(NSMutableArray *)networkArray{
    
    if (!_networkArray) {
        
        _networkArray = [NSMutableArray array];
    }
    return _networkArray;
}

-(instancetype)initWithStyle:(UITableViewStyle)style{
    
    if (self = [super initWithStyle:UITableViewStylePlain]) {
        
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
     NSLog(@"这个页面是 社区-->PersonalHomePageTableViewController");

    [self addButtonAtBotttom];
#pragma --判断进入当前页面时，按钮上的文字是关注还是取消关注===
    [self ToDetermineWhetherClickDisplays];
    
#pragma --判断上个页面传来的model--------
    if ([self.modelType isEqualToString:@"replyModel"]) {
//        点回复者头像传过来的

        AVQuery *query = [AVQuery queryWithClassName:@"_User"];
        [query whereKey:@"objectId" equalTo:self.personalID];
        AVUser *user = [[query findObjects] firstObject];
        //给头视图赋值
        [self headerViewAssignmentWith:user];
        
        [[MHDataHelper shareDataHelper] requestAllHerTopicWith:self.personalID didFinished:^(NSMutableArray *array) {
            
            self.allHerTopics = array;
            [self.tableView reloadData];
            
        }];

        [[MHDataHelper shareDataHelper] requestAllHerReplysWith:self.personalID didFinished:^(NSMutableArray *array) {
            
            self.allHerReplys = array;
            [self.tableView reloadData];
            
        }];
        
    }else{//不是点回复者头像传过来的
    //赋值

        AVUser *user = self.model.owner;
        
        [self headerViewAssignmentWith:user];
        
        [[MHDataHelper shareDataHelper] requestAllHerTopicWith:self.model.owner.objectId didFinished:^(NSMutableArray *array) {
            
            self.allHerTopics = array;
            [self.tableView reloadData];
            
        }];
        
        [[MHDataHelper shareDataHelper] requestAllHerReplysWith:self.model.owner.objectId didFinished:^(NSMutableArray *array) {
            
            self.allHerReplys = array;
            [self.tableView reloadData];
            
        }];
        
    }
        
}

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"这个页面是 社区-->PersonalHomePageTableViewController");
    self.tableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"blue.jpg"]];
    self.navigationController.navigationBarHidden = NO;//导航控制器不隐藏
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;//去除黑线
    self.tabBarController.tabBar.hidden = YES; //隐藏底部tabbar
    self.edgesForExtendedLayout = UIRectEdgeBottom;//===========新加
    //设置头视图
    [self setTableHeaderView];

    
    //注册两个cell
    UINib *replyNib = [UINib nibWithNibName:@"LReplyTableViewCell" bundle:[NSBundle mainBundle]];
    [self.tableView registerNib:replyNib forCellReuseIdentifier:@"LReplyCell"];
    [self.tableView registerClass:[TopicTableViewCell class] forCellReuseIdentifier:@"TopCell"];
    
    //已经成为好友
    [[EaseMob sharedInstance].chatManager asyncFetchBuddyListWithCompletion:^(NSArray *buddyList, EMError *error) {
        if (!error) {
            NSLog(@"获取成功 -- %@",buddyList);
            
            for (EMBuddy * obj in buddyList) {
                
                if ([obj.username isEqualToString:self.userModel[@"username"]]) {
                    
                    
                    [self.bottomButton.leftBtn setTitle:@"已经成为好友" forState:UIControlStateNormal];
                    self.bottomButton.leftBtn.enabled = NO;
                    
                }
                
            }
        }
    } onQueue:nil];
    
}
#pragma === 给头视图赋值 ==================
-(void)headerViewAssignmentWith:(AVUser *)user{
    
    self.headV.userNameLbl.text = user[@"nickname"];
    self.headV.headImV.image = [UIImage imageNamed:user[@"userImageName"]];
    self.headV.genderLbl.text = [user[@"gender"] stringByAppendingString:user[@"age"]];
    self.headV.constellationLbl.text = user[@"constellation"];

    
}

#pragma mark === 进入当前页面时，按钮的文字是关注/取消关注 =
-(void)ToDetermineWhetherClickDisplays{
    //从网络获取登录用户的大数组
    self.networkArray = [AVUser currentUser][@"myAttention"];
    
    //当前页面用户信息来自上个页面传来的findmodel（.h中的属性接受的）
    self.userModel = self.model.owner;
    
    //如果用户是当前登陆的用户，就不需要添加好友和关注
    if ([self.userModel.objectId isEqualToString:[AVUser currentUser].objectId]) {
        
        [self.bottomButton removeFromSuperview];
        
    }
    
    //判断是否包含
    if ([self.networkArray containsObject:self.userModel]||[self.networkArray containsObject:[AVUser currentUser]]) {
        //如果包含就设置为取消关注
        [self.bottomButton.rightBtn setTitle:@"取消关注" forState:(UIControlStateNormal)];
    }
    
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];

    //消失时移除底部的bottomButton
    [self.bottomButton removeFromSuperview];
    
    //设置导航栏透明
    [self.navigationController.navigationBar setBackgroundImage:[self imageWithBgColor:[UIColor colorWithRed:1 green:1 blue:1 alpha:1]] forBarMetrics:UIBarMetricsDefault];
}

#pragma mark ======== 导航栏颜色渐变 ==================

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{

    [self.navigationController.navigationBar setBackgroundImage:[self imageWithBgColor:[UIColor colorWithRed:0 green:1 blue:1 alpha:self.tableView.contentOffset.y / 100]] forBarMetrics:UIBarMetricsDefault];

}


-(UIImage *)imageWithBgColor:(UIColor *)color {
    
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    
    UIGraphicsBeginImageContext(rect.size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return image;
    
}

#pragma mark ======== 设置tableview的头视图 ===========

//设置头视图(声音签名属于头视图的一部分，底部的button)
-(void)setTableHeaderView{
    
    self.headV = [[HeadView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.tableView.frame), 200)];
    self.headV.backgroundColor = [UIColor whiteColor];
    self.tableView.tableHeaderView = self.headV;
    self.tableView.tableHeaderView.backgroundColor = [UIColor clearColor];
    
    //设置头视图下方的button（声音签名）
    [self.headV.voiceBtn setTitle:@"点击听TA的声音签名" forState:(UIControlStateNormal)];
    [self.headV.voiceBtn setTitleEdgeInsets:UIEdgeInsetsMake(0,0,5,0)];
    [self.headV.voiceBtn.titleLabel setTextAlignment:(NSTextAlignmentCenter)];//文字居中
    [self.headV.voiceBtn setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    [self.headV.voiceBtn addTarget:self action:@selector(clickVoiceBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
}

//点击声音签名Btn的事件
-(void)clickVoiceBtnAction:(UIButton*)sender{
    
     [[PlayerManager defaultManager] pausePlay];
    
    
    if ([self.modelType isEqualToString:@"replyModel"]) {
        
        AVUser *user = [AVUser objectWithoutDataWithObjectId:self.personalID];
        
        [[SKXRongCloudManager sharaManager] playRecordSuccessWithURL:user[@"myVoice"]];
        
    }else{
        
        [[SKXRongCloudManager sharaManager] playRecordSuccessWithURL:self.model.owner[@"myVoice"]];
        
    }
    
}


#pragma mark ========= 设置底部的两个按钮和点击事件 ======

//设置底部两个按钮
- (void)addButtonAtBotttom{
    
    self.bottomButton = [[CustomTwoBtnvView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.tableView.frame)-50, self.tableView.frame.size.width, 50) LeftBtnBgColor:[UIColor whiteColor] RightBtnBgColor:[UIColor whiteColor]];
    
    [self.bottomButton setLeftBtnTitle:@"+好友" RightBtnTitle:@"+关注" forState:UIControlStateNormal];
    
    
    [self.bottomButton setLeftBtnTitleColor:[UIColor greenColor] RightBtnTitleColor:[UIColor greenColor]];
    
    [self.navigationController.view addSubview:self.bottomButton];
    
    //添加事件
    [self.bottomButton.leftBtn addTarget:self action:@selector(addFriendBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.bottomButton.rightBtn addTarget:self action:@selector(attentionBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
}

//关注按钮
- (void)attentionBtnAction:(UIButton*)sender{
    //根据上面的文字执行操作

    if ([sender.titleLabel.text isEqualToString:@"+关注"]) {
        
        [sender setTitle:@"取消关注" forState:(UIControlStateNormal)];
        
        if ([self.modelType isEqualToString:@"replyModel"]) {
            
            AVUser *user = [AVUser objectWithoutDataWithObjectId:self.personalID];
            
            [self.networkArray addObject:user];
            
        }else{
        
        //保存当前页面用户信息
        [self.networkArray addObject:self.userModel];
            
             }
        
        //将保存的信息添加到leanCloud
            [[AVUser currentUser] setObject:self.networkArray forKey:@"myAttention"];
        
        [[AVUser currentUser] saveInBackground];
        
    }else if ([sender.titleLabel.text isEqualToString:@"取消关注"]){
        
        [sender setTitle:@"+关注" forState:(UIControlStateNormal)];
        
        //将当前页信息从leanCloud删除
        [self.networkArray removeObject:self.userModel];
        [[AVUser currentUser] setObject:self.networkArray forKey:@"myAttention"];
        [[AVUser currentUser] saveInBackground];
        
        }
 

}

//添加好友按钮(待完善)
- (void)addFriendBtnAction:(UIButton*)sender{
    
    [[SKXFriendManager sharaFriendManager] addFriendWithName:self.model.owner[@"username"]];

}

#pragma mark ======== Ta的主题/回复  button的点击事件 ===

//点击时刷新视图到对应的cell
- (void)clickLeftBtnAction:(UIButton*)sender{
    
    if (!flag) {
        flag = YES;
        [self.tableView reloadData];
    }
    
}
//点击时刷新视图到对应的cell
- (void)clickRightBtnAction:(UIButton*)sender{
    
    if (flag) {
        flag = NO;
    [self.tableView reloadData];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark ======== Table view data source的方法=====

//分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (self.allHerReplys.count) {
        
        ReplyModel *reply = self.allHerReplys[0];
        
        if ([reply.replyer[@"open"] isEqualToString:@"off"]) {
            
            return 1;
            }
    
        }
    
    
        if (flag) {
            
            return self.allHerTopics.count;
            
        }else{
            
            return self.allHerReplys.count;
            
        }

}

//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (self.allHerReplys.count && self.allHerTopics.count) {
        ReplyModel *reply = self.allHerReplys[0];
        
        if ([reply.replyer[@"open"] isEqualToString:@"off"]) {
            
            self.tableView.bounces = NO;
            
            return 300;
            
        }
    }
    
    if (flag == NO) {
        
        return self.view.frame.size.height/3.5;
        
    }else{
        
        return [self tableView:tableView cellForRowAtIndexPath:indexPath].height;
        
    }

}

//创建cell并赋值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    

        if (flag) {//传model - 他的话题
            FindModel *find = self.allHerTopics[_allHerTopics.count-1-indexPath.row];
            //
            
            if ([find.owner[@"open"] isEqualToString:@"off"]) {
                
                UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"cell"];
                if (indexPath.row == 0) {
                    cell.textLabel.text = @"该用户设置了隐私";
                    cell.textLabel.textAlignment = NSTextAlignmentCenter;
                    
                    return cell;
                }
                
            }

            
            TopicTableViewCell*cell = [[TopicTableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"TopCell"];
            //cell的子控件赋值
            [cell configureCellWithModel:find];
            cell.voiceBtn.tag = indexPath.row+101;
            [cell.voiceBtn addTarget:self action:@selector(listenHerTopic:) forControlEvents:(UIControlEventTouchUpInside)];
            cell.voiceBtn.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"btncolor.jpg"]];

            return cell;
            
        }else {//传model - 他的回复
            ReplyModel *reply = self.allHerReplys[_allHerReplys.count-1-indexPath.row];
            
            if ([reply.replyer[@"open"] isEqualToString:@"off"]) {
                
                UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"cell"];
                if (indexPath.row == 0) {
                    cell.textLabel.text = @"该用户设置了隐私";
                    cell.textLabel.textAlignment = NSTextAlignmentCenter;
                    return cell;
                }
            }
            
            LReplyTableViewCell*cell = [tableView dequeueReusableCellWithIdentifier:@"LReplyCell"];
                
            [cell configureCellWithReplyModel:reply];
            
            cell.voiceBtn.tag = indexPath.row+101;
            [cell.voiceBtn addTarget:self action:@selector(listenHerReply:) forControlEvents:(UIControlEventTouchUpInside)];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.voiceBtn.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"btncolor.jpg"]];

            return cell;
        }
    }


//他的话题
- (void)listenHerTopic:(UIButton *)sender{
    FindModel *find = self.allHerTopics[_allHerTopics.count+100-sender.tag];
    [[SKXRongCloudManager sharaManager] playRecordSuccessWithURL:find.messageVoice];
    
}


//他的回复
- (void)listenHerReply:(UIButton *)sender{
    ReplyModel *reply = self.allHerReplys[_allHerReplys.count+100-sender.tag];
    [[SKXRongCloudManager sharaManager] playRecordSuccessWithURL:reply.replyVoice];
}


//点击cell事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (flag) {
        FindModel *find = self.allHerTopics[_allHerTopics.count-1-indexPath.row];
        ReplyViewController*replyVC = [[ReplyViewController alloc]init];
        //        replyVC.ControlType = @"person";
        replyVC.findModel = find;
        [MHDataHelper shareDataHelper].pushIndex += 1;
        replyVC.ControlType = @"person";
        [self.navigationController pushViewController:replyVC animated:YES];
    }
    
    
}



//设置区头
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    

    CustomTwoBtnvView *HeaderVInSection = [[CustomTwoBtnvView alloc]initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 50) LeftBtnBgColor:[UIColor whiteColor] RightBtnBgColor:[UIColor whiteColor]];
    
    //初始时设置字体为红色（与加载的cell对应）
    [HeaderVInSection.leftBtn setTitleColor:[UIColor redColor] forState:(UIControlStateNormal)];
    [HeaderVInSection setLeftBtnTitle:@"Ta的主题" RightBtnTitle:@"Ta的回复" forState:(UIControlStateNormal)];
    
    //添加点击事件
    [HeaderVInSection.leftBtn addTarget:self action:@selector(clickLeftBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [HeaderVInSection.rightBtn addTarget:self action:@selector(clickRightBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
 
    //刷新视图后会走这个方法，更改button的字体颜色
    [self changeButtonColor:HeaderVInSection];
    
    return HeaderVInSection;
}

//更改button的字体颜色
- (void)changeButtonColor:(CustomTwoBtnvView*)custom{
    
    if (!flag) {

        [custom.leftBtn setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
        [custom.rightBtn setTitleColor:[UIColor redColor] forState:(UIControlStateNormal)];
        
    }else{
        
        [custom.leftBtn setTitleColor:[UIColor redColor] forState:(UIControlStateNormal)];
        [custom.rightBtn setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    }
  
}

//区头的高
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 50;
}

//区尾的高
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{

    return 5;
}



@end
